package com.css.fxfzfxqh.modules.ysx.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.css.fxfzfxqh.base.dict.service.DictService;
import com.css.fxfzfxqh.common.rest.JcsjRestManager;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.exceptions.BizException;
import com.css.fxfzfxqh.modules.ysx.entity.FxqhJzwYSX;
import com.css.fxfzfxqh.modules.ysx.entity.FxqhJzwYSXSub;
import com.css.fxfzfxqh.modules.ysx.param.FxqhJzwYSXParam;
import com.css.fxfzfxqh.modules.ysx.param.MatchingParam;
import com.css.fxfzfxqh.modules.ysx.service.JzwYSXRepository;
import com.css.fxfzfxqh.modules.ysx.service.JzwYSXService;
import com.css.fxfzfxqh.modules.ysx.verify.YsxVerifyHandler;
import com.css.fxfzfxqh.util.CreateGson;
import com.css.fxfzfxqh.util.PlatformObjectUtils;
import com.css.fxfzfxqh.util.PlatformSessionUtils;
import com.css.fxfzfxqh.zcpt.sys.entity.SUser;
import com.css.fxfzfxqh.zcpt.sys.service.SUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.*;

/**
 * @Author: zhangSongRui
 * @CreateTime: 2023/08/22
 * @Description: ysx
 */
@Service
@Slf4j
public class JzwYSXServiceImpl implements JzwYSXService {

    @Resource
    private JzwYSXRepository jzwYSXRepository;
    @Autowired
    YsxVerifyHandler ysxVerifyHandler;
    @Resource
    DictService dictService;
    @Resource
    JcsjRestManager jcsjRestManager;
    @Autowired
    private SUserService sUserService;
    private static final String BASICLIBRARPAGE = "basicLibrary/page";
    private static final String BYIDANDTYPE = "basicLibrary/getByIdAndType";
    private static final String DATAMATCHING = "customVulnerability/dataMatching";

    @Override
    public Map<String, Object> getPage(int curPage, int pageSize, FxqhJzwYSXParam fxqhJzwYSX) throws BizException {
        //写入设防烈度
        if ("0".equals(fxqhJzwYSX.getYsxType())) {//国家级
            JSONObject param = new JSONObject();
            param.put("province", fxqhJzwYSX.getProvince());
            param.put("city", fxqhJzwYSX.getCity());
            param.put("county", fxqhJzwYSX.getCounty());
            param.put("years", fxqhJzwYSX.getYear());
            param.put("use0", fxqhJzwYSX.getHousingUse1());
            param.put("use1", fxqhJzwYSX.getHousingUse2());
            param.put("userName", fxqhJzwYSX.getCreateName());
            param.put("structureType", fxqhJzwYSX.getStructureType1());
            param.put("structureType1", fxqhJzwYSX.getStructureType2());
            param.put("fortification", fxqhJzwYSX.getFortify());
            param.put("number", fxqhJzwYSX.getNumberOfFloors());
            param.put("startTime", fxqhJzwYSX.getStartTime());
            param.put("endTime", fxqhJzwYSX.getEndTime());
            param.put("page", curPage);
            param.put("rows", pageSize);
            JSONObject basicLibraryPage = jcsjRestManager.getBasicLibraryPageForGet(BASICLIBRARPAGE, param);
            JSONObject jsonObject = basicLibraryPage.getJSONObject("data");
            Map<String, Object> map = new HashMap();
            if (jsonObject!=null) {
                List<FxqhJzwYSX> list = JSONObject.parseArray(JSONObject.toJSONString(jsonObject.getJSONArray("rows")), FxqhJzwYSX.class);
                map.put("total", jsonObject.get("total"));
                map.put("rows", list);
            }else {
                map.put("total", 0);
                map.put("rows", new ArrayList<>());
            }
            return map;
        }
        return jzwYSXRepository.getPage(curPage, pageSize, fxqhJzwYSX);
    }

    @Override
    public List<String> getSfIntensity(FxqhJzwYSXParam param) {
        return jzwYSXRepository.getSfIntensity(param);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(List<FxqhJzwYSXSub> param) throws Exception{
        param.forEach(entity->{
            jzwYSXRepository.update(entity);
        });

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> uploadYsxInformation(MultipartFile file, String jsxType, String province, String city, String county, String roleType) {
        ImportParams params = new ImportParams();
        params.setHeadRows(3);
        // params.setVerifyHandler(ysxVerifyHandler);
        params.setNeedVerify(true);
        boolean res = false;
        Map<String, Object> map = new HashMap<>();
        try {
            InputStream inputStream = file.getInputStream();
            ExcelImportResult<FxqhJzwYSXParam> result = ExcelImportUtil.importExcelMore(inputStream, FxqhJzwYSXParam.class, params);
            List<FxqhJzwYSXParam> failList = result.getFailList();
            if (PlatformObjectUtils.isNotEmpty(failList)) {
                StringBuilder errorMsg = new StringBuilder("<font size='5px' color='red'>导入失败：</font>");
                for (FxqhJzwYSXParam fxqhJzwYSX : failList) {
                    errorMsg.append("<font size='4px' ><br>").append("第").append(fxqhJzwYSX.getRowNum() + 1).append("行： ").append(fxqhJzwYSX.getErrorMsg()).append("</font>");
                }
                map.put("res", res);
                map.put("mess", errorMsg);
                return map;
            }
            String userId = PlatformSessionUtils.getUserId();
            String userJson = sUserService.getUserById(userId);
            SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
            List<FxqhJzwYSXParam> resultData = result.getList();//解析excel
            StringBuilder userProvinceErrorMsg = new StringBuilder("<font size='4px' color='red'>导入失败,请修改后重新导入</font><br>");
            userProvinceErrorMsg.append("<font size='4px' color='red'>导入失败原因:</font>");
            boolean resFlag = true;
            if (PlatformObjectUtils.isNotEmpty(resultData)) {
                List<String> provinceList = Arrays.asList("1", "2", "3");
                List<String> cityList = Arrays.asList("2", "3");
                if (provinceList.contains(roleType)) {
                    for (FxqhJzwYSXParam resultDatum : resultData) {
                        if (!province.equals(resultDatum.getProvince())) {
                            resFlag = false;
                            userProvinceErrorMsg.append("<font size='4px' ><br>").append("第").append(resultDatum.getRowNum() + 1).append("行").append("的数据省不是用户所在省").append("</font><br>");
                        }
                        if (cityList.contains(roleType) && !city.equals(resultDatum.getCity())) {
                            resFlag = false;
                            userProvinceErrorMsg.append("<font size='4px' ><br>").append("第").append(resultDatum.getRowNum() + 1).append("行").append("的数据市不是用户所在市").append("</font><br>");
                        }
                        if ("3".equals(roleType) && !county.equals(resultDatum.getCounty())) {
                            resFlag = false;
                            userProvinceErrorMsg.append("<font size='4px' ><br>").append("第").append(resultDatum.getRowNum() + 1).append("行").append("的数据县不是用户所在县").append("</font><br>");
                        }
                    }
                    if (!resFlag) {
                        map.put("res", false);
                        map.put("mess", userProvinceErrorMsg);
                        return map;
                    }
                }
                List<String> isRepeat1 = new ArrayList<>();
                Map<String, String> isRepeat2 = new HashMap<>();
                for (FxqhJzwYSXParam fxqhJzwYSXParam : resultData) {
                    if (!isRepeat1.contains(fxqhJzwYSXParam.getProvince() + "-" + fxqhJzwYSXParam.getCity() + "-" + fxqhJzwYSXParam.getCounty())) {
                        isRepeat1.add(fxqhJzwYSXParam.getProvince() + "-" + fxqhJzwYSXParam.getCity() + "-" + fxqhJzwYSXParam.getCounty());
                        jzwYSXRepository.delete(fxqhJzwYSXParam.getProvince(), fxqhJzwYSXParam.getCity(), fxqhJzwYSXParam.getCounty(), jsxType);
                    }
                    String id = null;
                    String key2 = fxqhJzwYSXParam.getProvince() + fxqhJzwYSXParam.getCity() + fxqhJzwYSXParam.getCounty()
                            + fxqhJzwYSXParam.getStructureType1() + fxqhJzwYSXParam.getStructureType2() + fxqhJzwYSXParam.getFortify()
                            + fxqhJzwYSXParam.getYear() + fxqhJzwYSXParam.getHousingUse1() + fxqhJzwYSXParam.getHousingUse2()
                            + fxqhJzwYSXParam.getNumberOfFloors();
                    if (isRepeat2.containsKey(key2)) {
                        id = isRepeat2.get(key2);
                    } else {
                        fxqhJzwYSXParam.setYsxType(jsxType);
                        fxqhJzwYSXParam.setRoleType(roleType);
                        id = IdUtil.getSnowflakeNextIdStr();
                        fxqhJzwYSXParam.setCreateUser(userId);
                        fxqhJzwYSXParam.setCreateName(sUser.getUserName());
                        fxqhJzwYSXParam.setCreateTime(new Date());
                        fxqhJzwYSXParam.setId(id);
                        res = jzwYSXRepository.saveYsx(fxqhJzwYSXParam);
                        isRepeat2.put(key2, id);
                    }
                    FxqhJzwYSXSub jzwYSXSub = new FxqhJzwYSXSub();
                    jzwYSXSub.setPid(id);
                    jzwYSXSub.setIntensity(fxqhJzwYSXParam.getDamageDegree());
                    jzwYSXSub.setDamage("基本完好");
                    jzwYSXSub.setRate(org.apache.commons.lang3.StringUtils.isBlank(fxqhJzwYSXParam.getIntensity1()) ? "0" : (fxqhJzwYSXParam.getIntensity1() + "%"));
                    jzwYSXRepository.saveYsxSub(jzwYSXSub);
                    jzwYSXSub.setDamage("轻微破坏");
                    jzwYSXSub.setRate(org.apache.commons.lang3.StringUtils.isBlank(fxqhJzwYSXParam.getIntensity2()) ? "0" : (fxqhJzwYSXParam.getIntensity2() + "%"));
                    jzwYSXRepository.saveYsxSub(jzwYSXSub);
                    jzwYSXSub.setDamage("中等破坏");
                    jzwYSXSub.setRate(org.apache.commons.lang3.StringUtils.isBlank(fxqhJzwYSXParam.getIntensity3()) ? "0" : (fxqhJzwYSXParam.getIntensity3() + "%"));
                    jzwYSXRepository.saveYsxSub(jzwYSXSub);
                    jzwYSXSub.setDamage("严重破坏");
                    jzwYSXSub.setRate(org.apache.commons.lang3.StringUtils.isBlank(fxqhJzwYSXParam.getIntensity4()) ? "0" : (fxqhJzwYSXParam.getIntensity4() + "%"));
                    jzwYSXRepository.saveYsxSub(jzwYSXSub);
                    jzwYSXSub.setDamage("倒塌");
                    jzwYSXSub.setRate(org.apache.commons.lang3.StringUtils.isBlank(fxqhJzwYSXParam.getIntensity5()) ? "0" : (fxqhJzwYSXParam.getIntensity5() + "%"));
                    jzwYSXRepository.saveYsxSub(jzwYSXSub);
                }
            }
        } catch (Exception e) {
            if (e.getMessage().contains("不是合法")) {
                map.put("res", false);
                map.put("mess", "上传失败! 上传的文件模板有误,请检查表头是否改动！");
            }
            e.printStackTrace();
        }
        map.put("res", res);
        return map;
    }

    @Override
    public Map<String, Object> getPageById(FxqhJzwYSXParam fxqhJzwYSXParam) throws BizException {
        //写入设防烈度
        Map<String, Object> map = new HashMap();
        if ("0".equals(fxqhJzwYSXParam.getYsxType())) {//国家级
            JSONObject param = new JSONObject();
            param.put("pId", fxqhJzwYSXParam.getId());
            param.put("dataType", fxqhJzwYSXParam.getDataType());
            param.put("province",fxqhJzwYSXParam.getProvince());
            JSONObject basicLibraryById = jcsjRestManager.getBasicLibraryPageForGet(BYIDANDTYPE, param);
            List<FxqhJzwYSXSub> list = JSONObject.parseArray(JSONObject.toJSONString(basicLibraryById.getJSONArray("data")), FxqhJzwYSXSub.class);
            map.put("rows", list);
        } else {
            if (null != fxqhJzwYSXParam.getFortify()) {
                String valueByDictCodeAndKey = dictService.getValueByDictCodeAndKey("sfqk", fxqhJzwYSXParam.getFortify());
                fxqhJzwYSXParam.setFortify(valueByDictCodeAndKey);
            }
            List<FxqhJzwYSXSub> list = jzwYSXRepository.getPageSubById(fxqhJzwYSXParam.getId());
            map.put("rows", list);
        }
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveOrUpdate(MatchingParam matchingParam) throws BizException {
        JSONObject param = JSONObject.parseObject(JSONObject.toJSONString(matchingParam, SerializerFeature.WriteDateUseDateFormat));
        //String json="{\"province\":\"河北省\",\"city\":\"石家庄市\",\"county\":\"长安区\",\"structureType\":\"砌体结构\",\"structureType1\":\"砖混结构\",\"fortification\":\"6度\",\"yearsList\":[1,0,0,0,0,0],\"useList\":[0.1666666667,0.1666666667,0.1666666667,0.1666666667,0.1666666667,0.1666666667,0,0,0,0,0],\"csList\":[1,0]}";
        //JSONObject param = JSONObject.parseObject(json);
        JSONObject basicLibrary = jcsjRestManager.getBasicLibraryPageForPost(DATAMATCHING, param);
        System.out.println("basicLibrary================" + basicLibrary);
        JSONObject data = basicLibrary.getJSONObject("data");
        if (200 == basicLibrary.getInteger("code") && data.size() == 0) {
            return "-1";
        }
        System.out.println("data=======================" + data.toString());
        List<FxqhJzwYSXSub> list = JSONObject.parseArray(JSONObject.toJSONString(data.getJSONArray("countValue")), FxqhJzwYSXSub.class);
        FxqhJzwYSXParam fxqhJzwYSXParam = new FxqhJzwYSXParam();
        fxqhJzwYSXParam.setYsxType("3");
        fxqhJzwYSXParam.setCounty(matchingParam.getCounty());
        fxqhJzwYSXParam.setCity(matchingParam.getCity());
        fxqhJzwYSXParam.setProvince(matchingParam.getProvince());
        fxqhJzwYSXParam.setStructureType1(matchingParam.getStructureType());
        fxqhJzwYSXParam.setStructureType2(matchingParam.getStructureType1());
        fxqhJzwYSXParam.setFortify(matchingParam.getFortification());
        jzwYSXRepository.delete(fxqhJzwYSXParam);
        System.out.println("list================" + list);
        FxqhJzwYSXParam resultDatum = new FxqhJzwYSXParam();
        String userId = PlatformSessionUtils.getUserId();
        String userJson = sUserService.getUserById(userId);
        SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
        String id = IdUtil.getSnowflakeNextIdStr();
        resultDatum.setId(id);
        resultDatum.setCreateTime(new Date());
        resultDatum.setCreateUser(userId);
        resultDatum.setCreateName(sUser.getUserName());
        resultDatum.setYsxType("3");
        resultDatum.setRoleType(matchingParam.getRoleType());
        resultDatum.setCity(matchingParam.getCity());
        resultDatum.setCounty(matchingParam.getCounty());
        resultDatum.setProvince(matchingParam.getProvince());
        resultDatum.setStructureType1(matchingParam.getStructureType());
        resultDatum.setStructureType2(matchingParam.getStructureType1());
        resultDatum.setFortify(matchingParam.getFortification());
        jzwYSXRepository.saveYsx(resultDatum);

        for (FxqhJzwYSXSub jzwYSXSub : list) {
            jzwYSXSub.setPid(id);
            jzwYSXRepository.saveYsxSub(jzwYSXSub);
        }

        return id;
    }
}
